package com.aratek.huwai.controller;

import com.aratek.huwai.common.JsonArrayBuilder;
import com.aratek.huwai.common.R;
import com.aratek.huwai.dao.DishRepository;
import com.aratek.huwai.dao.ProgramRepository;
import com.aratek.huwai.dao.ProgramScoreRepository;
import com.aratek.huwai.dao.ScoreRepository;
import com.aratek.huwai.model.DishEntity;
import com.aratek.huwai.model.ProgramEntity;
import com.aratek.huwai.model.ProgramScoreEntity;
import com.aratek.huwai.model.ScoreEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author 姜寄羽
 * 专门用于API传输
 * @Date 2018/1/22 15:56
 */
@RestController
@RequestMapping
public class ApiController {

    private static final Logger LOG = LoggerFactory.getLogger(ApiController.class);

    @Autowired
    DishRepository dishRepository;

    @Autowired
    ScoreRepository scoreRepository;

    @Autowired
    ProgramRepository programRepository;

    @Autowired
    ProgramScoreRepository programScoreRepository;
    /***
     * 提交料理
     * @return
     */
    @Transactional
    @RequestMapping(value = "/menu",method = RequestMethod.POST)
    public R commitRequest(@RequestBody @Valid DishEntity dishEntity, BindingResult result){
        if(result.hasErrors()){
            return outputErrorMsg(result);
        }
        int count = dishRepository.countByTable(dishEntity.getTable());
        if(count != 0){
            return R.ok("您这桌已经上传过了料理，不能再次上传了。如果发现料理上传错误，请联系裁判处理");
        }
        dishEntity.setId(DishRepository.KEY.getAndIncrement());
        dishRepository.save(dishEntity);
        LOG.info("table {},name {}",dishEntity.getTable(),dishEntity.getName());
        return R.ok("料理提交成功");
    }

    /**
     * 提交打分
     * @return
     */
    @Transactional
    @RequestMapping(value = "/score",method = RequestMethod.POST)
    public R commitScore(@RequestBody @Valid ScoreEntity scoreEntity,BindingResult result){
        if(result.hasErrors()){
            return outputErrorMsg(result);
        }
        int count = scoreRepository
                .countByDishIdAndRaterTable(scoreEntity.getDishId(), scoreEntity.getRaterTable());
        if(count != 0){
            return R.ok("已经评价过的料理将不能再次评价。如发现料理评价上传错误，请联系裁判处理");
        }
        scoreEntity.setId(ScoreRepository.KEY.getAndIncrement());
        scoreRepository.save(scoreEntity);
        return R.ok("评分提交成功");
    }

    @Transactional
    @RequestMapping(value = "/programScore",method = RequestMethod.POST)
    public R commitProgramScore(@RequestBody @Valid ProgramScoreEntity scoreEntity, BindingResult result){
        if(result.hasErrors()){
            return outputErrorMsg(result);
        }
        int count = programScoreRepository
                .countByProgramIdAndRaterId(scoreEntity.getProgramId(), scoreEntity.getRaterId());
        if(count != 0){
            return R.ok("已经评价过的评分将不能再次评价。");
        }
        scoreEntity.setId(ProgramScoreRepository.KEY.getAndIncrement());
        programScoreRepository.save(scoreEntity);
        return R.ok("评分提交成功");
    }

    /**
     *
     * @return
     */
    @GetMapping("/dish")
    public R queryDish(@RequestParam("dishId") Integer dish){
        if(dish == null){
            return R.ok().put("dishName", "");
        }
        DishEntity entity = dishRepository.findOne(dish);
        if(entity!=null) {
            return R.ok().put("dishName", entity.getName());
        }else {
            return R.ok().put("dishName", "没有录入这个料理");
        }
    }

    @GetMapping("loadDish")
    public R loadDish(){
        Iterable<DishEntity> entities = dishRepository.findAll();
        JsonArrayBuilder arrayBuilder = JsonArrayBuilder.create();
        for(DishEntity entity : entities){
            arrayBuilder.addNew(entity);
        }
        return R.ok().put("dishes", arrayBuilder);
    }

    @GetMapping("loadProgram")
    public R loadProgram(){
        Iterable<ProgramEntity> entities = programRepository.findAll();
        JsonArrayBuilder arrayBuilder = JsonArrayBuilder.create();
        for(ProgramEntity entity : entities){
            arrayBuilder.addNew(entity);
        }
        return R.ok().put("programs", arrayBuilder);
    }

    private static R outputErrorMsg(BindingResult result) {
        List<ObjectError> list = result.getAllErrors();
        StringBuilder res = new StringBuilder();
        String prefix = "";
        for(ObjectError error : list){
            res.append(error.getDefaultMessage()).append(prefix);
            prefix = "<br/>";
        }
        return R.ok(res.toString());
    }

    @PostMapping("program")
    public R commitProgram(@RequestBody  @Valid  ProgramEntity entity,BindingResult result){
        if(result.hasErrors()){
            return outputErrorMsg(result);
        }
        int count = programRepository.countByNameEquals(entity.getName());
        if(count != 0){
            return R.ok("您已经上传过了该节目，不能再次上传了。");
        }
        entity.setId(ProgramRepository.KEY.getAndIncrement());
        programRepository.save(entity);
        LOG.info("program {},name {}",entity.getId(),entity.getName());
        return R.ok("节目提交成功");
    }
}
